package io.zcoder.innoway.activities;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.zcoder.innoway.R;
import io.zcoder.innoway.utils.Utils;
import io.zcoder.innoway.adapters.HistoryEntryTimeByMonthAdapter;
import io.zcoder.innoway.commons.Constants;
import io.zcoder.innoway.commons.PrefUtils;
import io.zcoder.innoway.models.EntryMonth;
import io.zcoder.innoway.models.EntryTimeResponse;
import io.zcoder.innoway.models.ResponseBase;
import io.zcoder.innoway.rest.RestClient;
import io.zcoder.innoway.widgets.TextViewCustom;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class TrendHistoryByMonthActivity extends BaseActivity {

    @BindView(R.id.list_history)
    RecyclerView mList;
    @BindView(R.id.current_time)
    TextViewCustom mCurrentTime;
    @BindView(R.id.backward)
    ImageView mBackward;
    @BindView(R.id.forward)
    ImageView mForward;
    @BindView(R.id.common_edit_text)
    TextViewCustom mEdit;
    @BindView(R.id.delete)
    TextViewCustom mDelete;
    @BindView(R.id.common_done)
    TextViewCustom mDone;

    @OnClick(R.id.common_done)
    void done() {
        if (mAdapter == null) {
            return;
        }
        mDone.setVisibility(View.GONE);
        mEdit.setVisibility(View.VISIBLE);
        mAdapter.setModeDelete(false);
        mDelete.setVisibility(View.GONE);

    }

    @OnClick(R.id.common_edit_text)
    void edit() {
        if (mAdapter == null) {
            return;
        }
        mAdapter.setModeDelete(true);
        mEdit.setVisibility(View.GONE);
        mDone.setVisibility(View.VISIBLE);
        mDelete.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.delete)
    void delete() {
        if (mAdapter == null) {
            return;
        }
        mListDelete = mAdapter.getItemDelete();
        if (mListDelete.isEmpty()) {
            return;
        }
        new MaterialDialog.Builder(this)
                .title(R.string.delete)
                .content(R.string.are_you_sure)
                .positiveText(R.string.yes)
                .negativeText(R.string.no)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showProgress();
                        deleteEntry(0);
                    }
                }).show();
    }

    @OnClick(R.id.backward)
    void backward() {
        if (mBackward.getAlpha() == 1) {
            mEntryMonth.setMonthPosition(mEntryMonth.getMonthPosition() - 1);
            setCurrentTime();
        }
    }

    @OnClick(R.id.forward)
    void forward() {
        if (mForward.getAlpha() == 1) {
            mEntryMonth.setMonthPosition(mEntryMonth.getMonthPosition() + 1);
            setCurrentTime();
        }
    }

    private EntryMonth mEntryMonth;
    private HistoryEntryTimeByMonthAdapter mAdapter;
    private List<Integer> mListDelete;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_history_entry_month_activity);
        ButterKnife.bind(this);

        showBack(true);
        mEntryMonth = getIntent().getParcelableExtra(Constants.ENTRY_MONTH_EXTRAS);
        if (mEntryMonth == null) {
            return;
        }
        mEdit.setVisibility(View.VISIBLE);
        setTitle(String.format(getString(R.string.history_s), getString(Utils.getIdEntry(mEntryMonth.getEntryPosition()))));
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        mList.setLayoutManager(layoutManager);
        setCurrentTime();
    }

    private void setCurrentTime() {
        mCurrentTime.setText(mEntryMonth.getLabelTime());
        if (mEntryMonth.isBack()) {
            mBackward.setAlpha(1);
        } else {
            mBackward.setAlpha(0.3f);
        }
        if (mEntryMonth.isNext()) {
            mForward.setAlpha(1);
        } else {
            mForward.setAlpha(0.3f);
        }
        getData();
    }

    private void getData() {
        String type = getString(Utils.getIdEntry(mEntryMonth.getEntryPosition())).toLowerCase().replace(" ", "_");
        RestClient.build(this, true).getEntryTimeOfMonth(PrefUtils.getInt(this, PrefUtils.PREF_PROFILE_ID),
                mEntryMonth.getStartDate(mEntryMonth.getMonthPosition()),
                mEntryMonth.getEndDate(mEntryMonth.getMonthPosition()), type,
                new Callback<EntryTimeResponse>() {
                    @Override
                    public void success(EntryTimeResponse entryTimeResponse, Response response) {
                        if (entryTimeResponse.getStatus_code() != 200) {
                            showAlert(getString(R.string.error), entryTimeResponse.getMessage());
                        } else {
                            String unit = "%";
                            int position = mEntryMonth.getEntryPosition();
                            if (position == 0) {
                                unit = Utils.getUnitWeight(mEntryMonth.getUnit());
                            }
                            if (position == 6) {
                                unit = "Kg";
                            }
                            if (position == 7) {
                                unit = "Kcal";
                            }

                            mAdapter = new HistoryEntryTimeByMonthAdapter(entryTimeResponse.getData(),
                                    unit);
                            mList.setAdapter(mAdapter);
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                    }
                });
    }

    private void deleteEntry(final int id) {
        RestClient.build(this, true).deleteEntry(mListDelete.get(id), PrefUtils.getInt(this, PrefUtils.PREF_PROFILE_ID), new Callback<ResponseBase>() {
            @Override
            public void success(ResponseBase responseBase, Response response) {
                if (responseBase.getStatus_code() != 200) {
                    hideProgress();
                    showAlert(getString(R.string.error), responseBase.getMessage());
                } else {
                    mListDelete.remove(id);
                    if (mListDelete.isEmpty()) {
                        hideProgress();
                        getData();
                    } else {
                        deleteEntry(0);
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
            }
        });

    }
}
